package com.auxgroup.smarthome.service;


import com.auxgroup.smarthome.repo.MenuRepo;
import com.auxgroup.smarthome.dto.MenuDto;
import com.auxgroup.smarthome.entity.MenuEntity;
import com.auxgroup.smarthome.session.SessionMenu;
import com.auxgroup.smarthome.syscode.Syscode;
import com.auxgroup.smarthome.web.ApiResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by kevinchen on 2016/12/27.
 */
@Service
public class MenuService {
    @Autowired
    private MenuRepo menuRepo;


    public MenuEntity get(String id) {
        return menuRepo.findOne(id);
    }

    public ApiResponse deleteMenuById(String id) {
        if (StringUtils.isBlank(id) || menuRepo.findOne(id) == null ){
            return ApiResponse.prompt(Syscode.DTO_PARAMS_ERROR);
        }
        menuRepo.delete(id);
        return ApiResponse.prompt(Syscode.SC_OK);
    }



    public List<SessionMenu> getShowAllMenus(){
        List<MenuEntity> allMenus = menuRepo.findAll();
        if (allMenus==null)return null;
        List<SessionMenu> allSessionMenus = new ArrayList<SessionMenu>();
        for (Iterator<MenuEntity> iterator = allMenus.iterator();iterator.hasNext();) {
            MenuEntity next = iterator.next();
            allSessionMenus.add(next.createSessionMenu());
        }
        return allSessionMenus;
    }


    public ApiResponse createMenu(MenuDto menuDto){
        MenuEntity menuEntity = menuDto.createMenuEntity(new MenuEntity());
        menuRepo.save(menuEntity);
        return ApiResponse.ok(menuEntity.getId());
    }

    public ApiResponse updateMenu(MenuDto menuDto){
        if (StringUtils.isBlank(menuDto.getMenuId())){
            return ApiResponse.prompt(Syscode.DTO_PARAMS_ERROR);
        }
        MenuEntity oldMenuEntity = menuRepo.findOne(menuDto.getMenuId());
        if (oldMenuEntity == null ){
            return ApiResponse.prompt(Syscode.DTO_PARAMS_ERROR);
        }
        MenuEntity menuEntity = menuDto.createMenuEntity(oldMenuEntity);
        menuRepo.save(menuEntity);
        return ApiResponse.prompt(Syscode.SC_OK);
    }



}
